import binascii
from hashlib import sha256
#from rlp.utils import ascii_chr


### if even: zero second nibble of first pair and ignore it.
HEX_SEQUENCE_ODD  = 1
HEX_SEQUENCE_EVEN = 2

### This data is dictionary.
asciihex_to_int = {}
int_to_asciihex = {}
for i, c in enumerate(b'0123456789abcdef'):
    asciihex_to_int[c] = i
    int_to_asciihex[i] = c


### Input string '0123456789abcdef', output b'0123456789abcdef'
def binstr(string):
    return bytes(string, 'utf-8')

### Input bytes b'f0ceb', output [15, 0, 12, 14, 11].
def binstr_to_subnib(string):
    nib = []
    for i in range(len(string)):
        nib.append(asciihex_to_int[string[i]])
    return nib

### Input bytes b'f0ceb', output [1, 15, 0, 12, 14, 11].
def binstr_to_nib(string):
    nib = []
    for i in range(len(string)):
        nib.append(asciihex_to_int[string[i]])
    if len(nib) % 2:
        nib = [HEX_SEQUENCE_ODD] + nib
    else:
        nib = [HEX_SEQUENCE_EVEN, 0] + nib
    return nib

### Input string 'abc', [0x61, 0x62, 0x63], then output [6, 1, 6, 2, 6, 3].
def str_to_nib(string):
    return binstr_to_nib(binstr(string))

### Input string '616263', output [2, 0, 6, 1, 6, 2, 6, 3].
### Input string '5616263', output [1, 5, 6, 1, 6, 2, 6, 3].
### The length of output is always even.
def hexdigest_to_nib(hexdigest):
    if len(hexdigest) % 2:
        nib = [HEX_SEQUENCE_ODD]
    else:
        nib = [HEX_SEQUENCE_EVEN, 0]
    nib += [int(char, 16) for char in hexdigest]
    return nib

### Input [6, 1, 6, 2, 6, 3], output b'abc'.
def subnib_to_binstr(nibblearr):
    binstring = b''
    for i in range(len(nibblearr)):
        binstring += binstr(chr(int_to_asciihex[nibblearr[i]]))
    return binstring

### Input [2, 0, 6, 1, 6, 2, 6, 3], output b'abc'.
def nib_to_binstr(nibblearr):
    if len(nibblearr) % 2:
        raise Exception("nibbles must be of even numbers")
    if nibblearr[0] == HEX_SEQUENCE_EVEN:
        starting_index = 2
    elif nibblearr[0] == HEX_SEQUENCE_ODD:
        starting_index = 1
    else:
        raise Exception("nibblearr starts with unexpected number:", nibblearr)
    return subnib_to_binstr(nibblearr[starting_index:])







